from elasticsearch_dsl import *
from elasticsearch_dsl.connections import connections
from elasticsearch_dsl.analysis import CustomAnalyzer as _CustomAnalyzer

__author__ = '骆杨'


es = connections.create_connection(hosts=['127.0.0.1'])


class CustomAnalyzer(_CustomAnalyzer):
    def get_analysis_definition(self):
        return {}


ik_analyser = CustomAnalyzer('ik_max_word', filter=['lowercase'])


class ArticleType(DocType):
    """
    伯乐在线文章类型
    """
    suggest = Completion(analyzer=ik_analyser)
    title = Text(analyzer='ik_max_word')
    tags = Text(analyzer='ik_max_word')
    url = Keyword()
    url_object_id = Keyword()
    create_date = Date()
    content = Text(analyzer='ik_max_word')
    comment_nums = Integer()
    praise_nums = Integer()
    fav_nums = Integer()
    front_image_url = Keyword()
    front_image_path = Keyword()

    class Meta:
        doc_type = 'article'
        index = 'jobbole'

    class Index:
        doc_type = 'article'
        index = 'jobbole'


if __name__ == '__main__':
    res = es.search(index='jobbole',
                    body={
                        "query": {
                            "multi_match": {
                                "query": "python",
                                "fields": ["tags", "title", "content"]
                            }
                        },
                        "from": 0,
                        "size": 10,
                        "highlight": {
                            "fields": {
                                "title": {},
                                "content": {}
                            }
                        }
                    })
    total_nums = res['hits']['total']
    hit_list = []
    for hit in res['hits']['hits']:
        hit_dict = {}
        if 'title' in hit['highlight']:
            hit_dict['title'] = hit['highlight']['title']
        else:
            hit_dict['title'] = hit['_source']['title']
        if 'content' in hit['highlight']:
            hit_dict['content'] = hit['highlight']['content'][:500]
        else:
            hit_dict['content'] = hit['_source']['content'][:500]
        hit_dict['url'] = hit['_source']['url']
        hit_dict['create_date'] = hit['_source']['create_date']
        hit_dict['score'] = hit['_score']
        hit_list.append(hit_dict)
    print(hit_list)
